"""
TodoList 后端管理类
负责处理所有待办事项的CRUD操作和数据持久化
"""

import json
import os
import sys
from datetime import datetime, date
from pathlib import Path
from typing import List, Dict, Optional
from config import APP_CONFIG


class TodoManager:
    """
    待办事项管理器
    
    功能包括：
    - 添加新的待办事项
    - 删除指定的待办事项  
    - 更新待办事项内容
    - 切换完成状态
    - 获取所有待办事项
    - 数据持久化到JSON文件
    """
    
    def __init__(self, data_file: str = None):
        """
        初始化TodoManager
        
        Args:
            data_file (str): 存储待办事项的JSON文件路径，None则自动确定
        """
        if data_file is None:
            # 自动确定数据文件路径
            if getattr(sys, 'frozen', False):
                # 打包后的环境 - 将数据保存在exe文件同级目录，避免_internal
                exe_path = Path(sys.executable)
                base_path = exe_path.parent  # TodoList.exe所在目录
                data_dir = base_path / "data"
            else:
                # 开发环境 - 将数据保存在项目目录
                base_path = Path(__file__).parent
                data_dir = base_path / "data"

            # 确保数据目录存在
            data_dir.mkdir(exist_ok=True)
            self.data_file = str(data_dir / "todos.json")
            print(f"数据文件路径: {self.data_file}")
        else:
            self.data_file = data_file


        self.todos: List[Dict] = []
        self.load_todos()
    
    def load_todos(self) -> None:
        """
        从JSON文件加载待办事项数据
        如果文件不存在则创建空的待办事项列表
        """
        try:
            # 确保data目录存在
            os.makedirs(os.path.dirname(self.data_file), exist_ok=True)
            
            if os.path.exists(self.data_file):
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    self.todos = json.load(f)
                print(f"成功加载 {len(self.todos)} 个待办事项")
            else:
                self.todos = []
                print("数据文件不存在，创建新的待办事项列表")
                
        except Exception as e:
            print(f"加载待办事项数据时出错: {e}")
            self.todos = []
    
    def save_todos(self) -> bool:
        """
        保存待办事项数据到JSON文件
        
        Returns:
            bool: 保存成功返回True，失败返回False
        """
        try:
            # 确保data目录存在
            os.makedirs(os.path.dirname(self.data_file), exist_ok=True)
            
            with open(self.data_file, 'w', encoding='utf-8') as f:
                json.dump(self.todos, f, ensure_ascii=False, indent=2)
            print(f"成功保存 {len(self.todos)} 个待办事项到文件")
            return True
            
        except Exception as e:
            print(f"保存待办事项数据时出错: {e}")
            return False
    
    def add_todo(self, content: str) -> Dict:
        """
        添加新的待办事项
        
        Args:
            content (str): 待办事项内容
            
        Returns:
            Dict: 新创建的待办事项对象
        """
        if not content or not content.strip():
            raise ValueError("待办事项内容不能为空")
        
        # 生成新的ID（基于时间戳）
        todo_id = int(datetime.now().timestamp() * 1000)
        
        new_todo = {
            "id": todo_id,
            "content": content.strip(),
            "completed": False,
            "created_at": datetime.now().isoformat(),
            "updated_at": datetime.now().isoformat()
        }
        
        self.todos.append(new_todo)
        self.save_todos()
        
        print(f"添加新待办事项: {content}")
        return new_todo
    
    def delete_todo(self, todo_id: int) -> bool:
        """
        删除指定ID的待办事项
        
        Args:
            todo_id (int): 待办事项ID
            
        Returns:
            bool: 删除成功返回True，未找到返回False
        """
        for i, todo in enumerate(self.todos):
            if todo["id"] == todo_id:
                deleted_todo = self.todos.pop(i)
                self.save_todos()
                print(f"删除待办事项: {deleted_todo['content']}")
                return True
        
        print(f"未找到ID为 {todo_id} 的待办事项")
        return False
    
    def update_todo(self, todo_id: int, new_content: str) -> bool:
        """
        更新指定ID的待办事项内容
        
        Args:
            todo_id (int): 待办事项ID
            new_content (str): 新的内容
            
        Returns:
            bool: 更新成功返回True，未找到返回False
        """
        if not new_content or not new_content.strip():
            raise ValueError("待办事项内容不能为空")
        
        for todo in self.todos:
            if todo["id"] == todo_id:
                old_content = todo["content"]
                todo["content"] = new_content.strip()
                todo["updated_at"] = datetime.now().isoformat()
                self.save_todos()
                print(f"更新待办事项: '{old_content}' -> '{new_content}'")
                return True
        
        print(f"未找到ID为 {todo_id} 的待办事项")
        return False
    
    def toggle_complete(self, todo_id: int) -> bool:
        """
        切换指定ID的待办事项完成状态
        
        Args:
            todo_id (int): 待办事项ID
            
        Returns:
            bool: 切换成功返回True，未找到返回False
        """
        for todo in self.todos:
            if todo["id"] == todo_id:
                todo["completed"] = not todo["completed"]
                todo["updated_at"] = datetime.now().isoformat()
                self.save_todos()
                
                status = "完成" if todo["completed"] else "未完成"
                print(f"切换待办事项状态: '{todo['content']}' -> {status}")
                return True
        
        print(f"未找到ID为 {todo_id} 的待办事项")
        return False
    
    def get_todos(self) -> List[Dict]:
        """
        获取所有待办事项列表
        
        Returns:
            List[Dict]: 待办事项列表，按创建时间倒序排列
        """
        # 按创建时间倒序排列（最新的在前面）
        sorted_todos = sorted(self.todos, key=lambda x: x["created_at"], reverse=True)
        return sorted_todos
    
    def get_todos_by_date(self, target_date: str = None) -> Dict[str, List[Dict]]:
        """
        按日期分组获取待办事项
        
        Args:
            target_date (str, optional): 目标日期，格式 'YYYY-MM-DD'，默认为今天
            
        Returns:
            Dict[str, List[Dict]]: 包含今日和昨日任务的字典
        """
        if target_date is None:
            today = date.today()
        else:
            today = datetime.strptime(target_date, '%Y-%m-%d').date()
        
        yesterday = today.replace(day=today.day - 1) if today.day > 1 else \
                   today.replace(month=today.month - 1, day=31) if today.month > 1 else \
                   today.replace(year=today.year - 1, month=12, day=31)
        
        today_str = today.isoformat()
        yesterday_str = yesterday.isoformat()
        
        today_pending = []
        today_completed = []
        yesterday_tasks = []
        
        for todo in self.todos:
            # 提取任务的创建日期
            created_date = datetime.fromisoformat(todo["created_at"]).date().isoformat()
            
            if created_date == today_str:
                if todo["completed"]:
                    today_completed.append(todo)
                else:
                    today_pending.append(todo)
            elif created_date == yesterday_str:
                yesterday_tasks.append(todo)
        
        # 按创建时间排序
        today_pending.sort(key=lambda x: x["created_at"], reverse=True)
        today_completed.sort(key=lambda x: x["created_at"], reverse=True)
        yesterday_tasks.sort(key=lambda x: x["created_at"], reverse=True)
        
        return {
            "today_pending": today_pending,
            "today_completed": today_completed,
            "yesterday_tasks": yesterday_tasks
        }
    
    def get_today_stats(self) -> Dict:
        """
        获取今日任务统计信息
        
        Returns:
            Dict: 包含今日任务统计的字典
        """
        today = date.today().isoformat()
        
        today_tasks = [
            todo for todo in self.todos 
            if datetime.fromisoformat(todo["created_at"]).date().isoformat() == today
        ]
        
        total_today = len(today_tasks)
        completed_today = sum(1 for todo in today_tasks if todo["completed"])
        pending_today = total_today - completed_today
        completion_rate = round(completed_today / total_today * 100, 1) if total_today > 0 else 0
        
        return {
            "total": total_today,
            "completed": completed_today,
            "pending": pending_today,
            "completion_rate": completion_rate
        }
    
    def get_stats(self) -> Dict:
        """
        获取待办事项统计信息
        
        Returns:
            Dict: 包含总数、已完成数、未完成数的统计信息
        """
        total = len(self.todos)
        completed = sum(1 for todo in self.todos if todo["completed"])
        pending = total - completed
        completion_rate = round(completed / total * 100, 1) if total > 0 else 0
        
        return {
            "total": total,
            "completed": completed,
            "pending": pending,
            "completion_rate": completion_rate
        }


# 创建全局TodoManager实例
todo_manager = TodoManager()


class Api:
    """
    PyWebView API类
    将TodoManager的方法暴露给前端JavaScript调用
    """
    
    def get_todos(self):
        """获取所有待办事项"""
        return todo_manager.get_todos()
    
    def add_todo(self, content):
        """添加新待办事项"""
        try:
            return todo_manager.add_todo(content)
        except ValueError as e:
            return {"error": str(e)}
    
    def delete_todo(self, todo_id):
        """删除待办事项"""
        return todo_manager.delete_todo(int(todo_id))
    
    def update_todo(self, todo_id, content):
        """更新待办事项内容"""
        try:
            return todo_manager.update_todo(int(todo_id), content)
        except ValueError as e:
            return {"error": str(e)}
    
    def toggle_complete(self, todo_id):
        """切换完成状态"""
        return todo_manager.toggle_complete(int(todo_id))
    
    def get_stats(self):
        """获取统计信息"""
        return todo_manager.get_stats()
    
    def get_today_stats(self):
        """获取今日任务统计信息"""
        return todo_manager.get_today_stats()
    
    def get_todos_by_date(self, target_date=None):
        """按日期获取任务"""
        return todo_manager.get_todos_by_date(target_date)

    def get_app_config(self):
        """获取应用配置信息"""
        return APP_CONFIG


# 导出API实例供main.py使用
api = Api()

